'use strict'
angular.module('app')
    .directive('adminiDivision', function () {
        return {
            restrict: 'E',
            scope: {
                showAdminiDivision: '=showDivision',
                selectedPlace: '=',
                isEmpty: '&'
            },
            transclude: true,
            templateUrl: './src/app/launchplan/adminiDivision.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {
                $scope.targetPlace = '' //搜索框清空
                $scope.dropShow = false; //搜索下拉框默认隐藏
                if ($scope.selectedPlace) {
                    var origionPlace = JSON.parse(JSON.stringify($scope.selectedPlace))
                }
                //一级区域获取
                $.ajax({
                    url: $rootScope.app.project_name + '/zzyLaunchPlan/getChCity',
                    data: {
                        cityId:'10000'
                    }
                }).then(function (res) {
                    if (res.httpCode == 200) {
                        $scope.$apply(function () {
                            console.log(res)
                            $scope.provinces = res.data.filter(function (v) {
                                return v.region_type == '1'
                            });
                            checkSelect()
                        })
                    } else {
                        $rootScope.alertModal({"content":"系统异常"});
                    }
                })
                //点击一级获取二级区域
                $scope.showCity = function (province) {
                    if (!province.cityList) {
                        $.ajax({
                            url: $rootScope.app.project_name + '/zzyLaunchPlan/getChCity',
                            data: {
                                cityId:province.id
                            }
                        }).then(function (res) {
                            console.log(res);
                            if (res.httpCode == 200) {
                                $scope.$apply(function () {
                                    province.cityList = res.data
                                    checkSelect()
                                })
                            } else {
                                $rootScope.alertModal({"content":"系统异常"});
                            }
                        })
                    }
                    province.open = province.open ? !province.open : true
                }

                //点击二级获取三级区域
                $scope.showCounty = function (city) {
                    if (!city.countyList) {
                        $.ajax({
                            url: $rootScope.app.project_name + '/zzyLaunchPlan/getChCity',
                            data: {
                                cityId:city.id
                            }
                        }).then(function (res) {
                            console.log(res);
                            if (res.httpCode == 200) {
                                $scope.$apply(function () {
                                    city.countyList = res.data
                                    checkSelect()
                                })
                            } else {
                                $rootScope.alertModal({"content":"系统异常"});
                            }
                        })
                    }
                    city.open = city.open ? !city.open : true
                }

                // 勾选操作
                $scope.addPlace2 = function () {
                    console.log($scope.selectedPlace)

                    var len = arguments.length;
                    for (var i = 0; i < $scope.selectedPlace.length; i++) {
                        if ($scope.selectedPlace[i].id == arguments[0].id) {
                            $scope.selectedPlace.splice(i, 1)
                            $timeout(function () {
                                checkSelect();
                            }, 0)
                            return false
                        }
                    }
                    $scope.selectedPlace.push({ name: arguments[0].name, id: arguments[0].id })
                    $timeout(function () {
                        checkSelect();
                    }, 0)

                }

                $scope.addPlace = function () {
                    console.log($scope.selectedPlace)
                    var len = arguments.length;
                    for (var i = 0; i < $scope.selectedPlace.length; i++) {
                        var idArr = $scope.selectedPlace[i].id.split(',')
                        // console.log(idArr)
                        if (idArr[idArr.length - 1] == arguments[len - 2].id) {
                            $scope.selectedPlace.splice(i, 1)
                            return false
                        }
                    }
                    if (len == 2) {
                        $scope.selectedPlace.push({ name: arguments[0].text, id: arguments[0].id })
                    } else if (len == 3) {
                        $scope.selectedPlace.push({
                            name: arguments[0].text + '/' + arguments[1].text,
                            id: arguments[0].id + ',' + arguments[1].id
                        })
                    } else if (len == 4) {
                        $scope.selectedPlace.push({
                            name: arguments[0].text + '/' + arguments[1].text + '/' + arguments[2].text,
                            id: arguments[0].id + ',' + arguments[1].id + ',' + arguments[2].id
                        })
                    }
                }

                // 勾选回显
                function checkSelect() {
                    function isEqual(o) {
                        if ($scope.selectedPlace.length == 0) {
                            return false
                        }
                        var idList = $scope.selectedPlace.reduce(function (pre, cur) {
                            var idArr = cur.id.split(',')
                            pre.push(idArr[idArr.length - 1])
                            return pre
                        }, [])
                        // console.log(o)
                        return idList.some(function (t) {
                            return o.id == t
                        })
                    }

                    // setTimeout(function () {
                    // $scope.$apply(function () {
                    // console.log(Object.prototype.toString.call($scope.provinces))
                    $scope.provinces.forEach(function (t) {
                        t.checked = isEqual(t)
                        if (t.cityList && t.cityList.length) {
                            t.cityList.forEach(function (m) {
                                m.checked = isEqual(m)
                                if (m.countyList && m.countyList.length) {
                                    m.countyList.forEach(function (n) {
                                        n.checked = isEqual(n)
                                    })
                                }
                            })
                        }
                    })
                    // })
                    // }, 0)
                    if ($scope.matchResults) {
                        $scope.matchResults.forEach(function (t) {
                            var idArr = t.id.split(',')
                            t.checked = isEqual({ id: idArr[idArr.length - 1] })
                        })
                    }
                }

                $scope.deleteAll = function () {
                    $scope.selectedPlace = [];
                    checkSelect();
                }
                $scope.remove = function (index) {
                    $scope.selectedPlace.splice(index, 1)
                    checkSelect()
                }

                $scope.submit = function (v) {
                    if (v == '1') {
                        $scope.selectedPlace = origionPlace
                    } else if (v == '2') {

                    }
                    $scope.showAdminiDivision = false
                    if ($scope.selectedPlace.length == 0) {  // 已选区域为零默认选择不限
                        $scope.setPlace = '0'
                    }
                }
                //搜索城市
                $scope.search = function () {
                    // alert(123)
                    if (!$scope.targetPlace) return
                    $.ajax({
                        url : $rootScope.app.project_name+'/zzyLaunchPlan/searchCity',
                        data: {'cityName':  $scope.targetPlace}
                    }).then(function (res) {
                        console.log(res)
                        if (res.httpCode == 200) {
                            $scope.$apply(function () {
                                // console.log(res.records.length)
                                if (!res.data.length) {
                                    $scope.dropShow = false //搜索数据为空，隐藏下拉框
                                    return // 搜索城市不存在，查询到的数组为空
                                }
                                $scope.matchResults = res.data
                                $scope.dropShow = true
                                checkSelect()
                            })
                        } else {
                            $rootScope.alertModal({"content":"系统异常"});
                        }
                    })
                }

                //点击界面隐藏下拉框
                $scope.containHidden = function (e) {
                    $scope.dropShow = false
                }

                function stopPropagation(e) {
                    if (e.stopPropagation)
                        e.stopPropagation();
                    else
                        e.cancelBubble = true;
                }
                //点击自身下拉框不隐藏
                $scope.containShow = function (e) {
                    stopPropagation(e)
                }
            }]
        }
    })
    .directive('commercialArea', function () {
        return {
            restrict: 'E',
            scope: {
                selectedCounty: '=tradingArea',
                showCommercialArea: '=showCommercial',
                tradingAreaTypes: '=',
                circleList: '=',
                isEmpty: '&'
            },
            transclude: true,
            templateUrl: './src/app/zzy/launchplan/setTactics/commercialArea.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {
                if ($scope.selectedCounty) {
                    var oragionSelectedCounty = JSON.parse(JSON.stringify($scope.selectedCounty))
                    console.log(oragionSelectedCounty)
                }
                $scope.tradingAreaTypes = '1'
                // 商圈城市列表接口
                // ajaxRquest.getData('/zzyPopularCrt/getBusinessAreaCities').then(function (res) {
                //     $scope.formatProvinceList(res.records)
                // })
                $scope.defaultProvince = '上海'
                // $scope.province=[]
                $scope.province = [
                    {id: '北京', value: '北京'},
                    {id: '上海', value: '上海'},
                    {id: '广州', value: '广州'},
                    {id: '杭州', value: '杭州'},
                    {id: '深圳', value: '深圳'}
                ]
                // 对从后台获取的数据进行格式化
                $scope.formatProvinceList = function (v) {
                    var provinceObj = v.reduce(function (pre, cur) {
                        pre[cur.province] = cur.province
                        return pre
                    }, {})
                    for (var item in provinceObj) {
                        var obj = {}
                        $scope.$apply(function () {
                            obj.id = item
                            obj.value = item
                            $scope.province.push(obj)
                        })
                    }
                }
                // 输入城市名称获取对应城市的二级区域
                $scope.changeProvince = function (v) {
                    $scope.zoneList = []
                    $.ajax({
                        url : $rootScope.app.project_name+'/zzyLaunchPlan/getBusinessAreas',
                        data: {
                            businessAreaCities: '[{"city": "'+v+'"}]'
                        }
                    }).then(function (res) {
                        if (res.httpCode == 200) {
                            // console.log(res)
                            $scope.formatZoneList(res.data)
                        } else {
                            $scope.alertModal({"content":"系统异常"});
                        }
                    })
                }
                // 页面加载后进行初始化
                $scope.changeProvince($scope.defaultProvince)
                // 定义区和县的列表
                $scope.formatZoneList = function (v) {
                    var zoneObj = v.reduce(function (pre, cur) {
                        pre[cur.district] ? pre[cur.district].push({
                            baName: cur.baName,
                            baId: cur.baId,
                            checked: false
                        }) : pre[cur.district] = [{
                            baName: cur.baName,
                            baId: cur.baId,
                            checked: false
                        }]
                        return pre
                    }, {})
                    for (var i in zoneObj) {
                        var obj = {}
                        $scope.$apply(function () {
                            obj.name = i
                            obj.value = zoneObj[i]
                            $scope.zoneList.push(obj)
                        })
                    }
                    checkSelect()
                }
                // 已选商圈列表
                $scope.formatSelectedCounty = function (v) {
                    for (var i = 0; i < $scope.selectedCounty.length; i++) {
                        if ($scope.selectedCounty[i].baId == v.baId) {
                            $scope.selectedCounty.splice(i, 1)
                            return false
                        }
                    }
                    $scope.selectedCounty.push(v)
                }
                // 移除已选择商圈
                $scope.removeCounty = function (v, index) {
                    $scope.selectedCounty.splice(index, 1)
                    checkSelect()
                }

                // 根据已选择商圈改变复选框状态
                function checkSelect () {
                    function isEqual (o) {
                        if ($scope.selectedCounty.length === 0) {
                            return false
                        }
                        return $scope.selectedCounty.some(function (t) {
                            return o.baName == t.baName
                        })
                    }

                    setTimeout(function () {
                        $scope.$apply(function () {
                            $scope.zoneList.forEach(function (t) {
                                t.value.forEach(function (o) {
                                    o.checked = isEqual(o)
                                })
                            })
                        })
                    }, 0)
                }

                $scope.submit = function (v) {
                    $scope.showCommercialArea = false
                    if (v == '1') {
                        $scope.selectedCounty = oragionSelectedCounty
                    } else if (v == '2') {
                    }
                    $scope.isEmpty({a: $scope.selectedCounty.length + $scope.circleList.length})
                }
                $scope.isCircleListEmpty = function () {
                    $scope.isEmpty({a: $scope.selectedCounty.length + $scope.circleList.length})
                }
            }]
        }
    })
    .directive('map', function () {
        return {
            restrict: 'E',
            scope: {
                circleList: '=',
                close: '=',
                isCircleListEmpty: '&'
            },
            templateUrl: './src/app/zzy/launchplan/setTactics/map.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {
                // 百度地图API功能
                var map = new BMap.Map('allmap', {minZoom: 4, maxZoom: 15, enableMapClick: false})
                var point = new BMap.Point()
                $scope.selectPlaceList = []
                // if ($scope.circleList) {
                var origionList = JSON.parse(JSON.stringify($scope.circleList))
                // }
                $scope.results = []

                // 百度地图API功能
                map.centerAndZoom(point, 12)
                map.enableScrollWheelZoom(); // 启用滚轮放大缩小，默认禁用
                map.enableContinuousZoom(); // 启用地图惯性拖拽，默认禁用
                function myFun (result) {
                    var cityName = result.name
                    map.setCenter(cityName)
                }

                var myCity = new BMap.LocalCity()
                myCity.get(myFun)
                var navigationControl = new BMap.NavigationControl({
                    // 靠左上角位置
                    anchor: BMAP_ANCHOR_TOP_LEFT,
                    // LARGE类型
                    type: BMAP_NAVIGATION_CONTROL_LARGE,
                    // 启用显示定位
                    enableGeolocation: false
                })
                map.addControl(navigationControl)
                map.disableDoubleClickZoom()
                var preMarker = ''
                var circle = null
                var opts = {
                    width: 250, // 信息窗口宽度
                    height: 130, // 信息窗口高度
                    title: '', // 信息窗口标题
                    offset: {width: 0, height: -20},
                    enableMessage: true, // 设置允许信息窗发送短息
                    message: ''
                }
                var sContent =
                    "<h4 style='margin:0 0 5px 0;padding:0.2em 0'></h4>" +
                    "<p style='margin:0;line-height:1.5;margin-bottom: 10px'><input type='text' style='width: 100%;box-sizing: border-box' id='BdMapSelectInfo'></p>" +
                    "<p style='margin:0;line-height:1.5;margin-bottom: 10px'><span id='distance'></span></p>" +
                    "<p style='margin:0;line-height:1.5;font-size:13px;text-indent:2em'><input type='range' oninput='angular.element(this).scope().changeRank(this)' id='distanceInput'  max='5000' min='100' value='1500' step='0.5' ></p>" +
                    "<p style='margin:0;line-height:1.5;font-size:13px;margin-top: 10px;overflow: hidden'><button  style='border: none;width: 50px;height: 30px;background: #15608f;padding: 5px 10px;color: #fff;font-size: 14px;float: right;line-height:1em'  onclick='angular.element(this).scope().confirm(this)'>确定</button></p>" +
                    '</div>'
                var infoWindow = new BMap.InfoWindow(sContent, opts); // 创建信息窗口对象
                var k = 0
                var point = null
                var marker = null

                function mapClick (point) {
                    map.clearOverlays(circle)
                    circle = null
                    // if (map.getZoom() !== 15) {
                    map.centerAndZoom(point, 15)
                    // } else {
                    //     map.panTo(point)
                    // }
                    map.openInfoWindow(infoWindow, point)
                    circle = new BMap.Circle(point, 1500, {strokeWeight: 2, fillColor: '#60f59f'})
                    map.addOverlay(circle)
                    marker = new BMap.Marker(point); // 创建标注
                    // map.removeOverlay(preMarker)
                    map.addOverlay(marker)
                    // preMarker = marker
                    var geocoder = new BMap.Geocoder()
                    // 获取位置
                    // if(){
                    geocoder.getLocation(point, function (rs) {
                        // 获取地理组件
                        var addComp = rs.addressComponents
                        // 获取省份
                        var province = addComp.province
                        // 获取城市
                        var city = addComp.city
                        // 获取区县
                        var district = addComp.district
                        // 获取街道
                        var street = addComp.street
                        // 获取街道号
                        var streetNumber = addComp.streetNumber
                        $('#BdMapSelectInfo').val(city + district + street + streetNumber)
                    })
                    $('#distance').html(1.5 + 'Km')
                    // }
                }

                $scope.selfDefineFn = function () {
                    map.removeEventListener('click', addClick)
                    map.addEventListener('click', addClick)
                }

                function addClick (e) {
                    mapClick(e.point)
                }

                $scope.changeRank = function (v) {
                    circle.setRadius(v.value)
                    $('#distance').html((v.value / 1000).toFixed(1) + 'Km')
                }
                $scope.confirm = function () {
                    $scope.selfDefine = false
                    map.removeEventListener('click', addClick)
                    if ($scope.selectPlaceList.indexOf($('#BdMapSelectInfo').val()) == -1) {
                        circle.disableMassClear() // 禁止删除圆形覆盖物
                        marker.disableMassClear() // 禁止删除中心点图标
                        $scope.selectPlaceList.push($('#BdMapSelectInfo').val())
                        circle.setFillColor('#fc7878')
                        circle.setStrokeColor('red')
                        map.closeInfoWindow(); // 关闭信息提示框
                        $scope.$apply(function () {
                            $scope.results.push({
                                area: circle,
                                marker: marker,
                                latitude: circle.point.lat,
                                longitude: circle.point.lng,
                                baName: $('#BdMapSelectInfo').val(),
                                distance: $('#distanceInput').val()
                            })
                            $scope.circleList.push({
                                latitude: circle.point.lat,
                                longitude: circle.point.lng,
                                baName: $('#BdMapSelectInfo').val(),
                                distance: $('#distanceInput').val()
                            })
                        })
                    } else {
                        $rootScope.alertModel({
                            text: '商圈重复',
                            resCode: '00001'
                        })
                    }
                }
                infoWindow.addEventListener('close', function (e) {
                    map.clearOverlays(circle) // 关闭圆形覆盖物
                    $('#distanceInput').val(1500)
                })
                $scope.clearCircle = function (index) {
                    $scope.results[index].area.enableMassClear() // 重新让圆形覆盖物可以删除
                    $scope.results[index].marker.enableMassClear() // 重新让中心点标记可以删除
                    map.clearOverlays($scope.results[index].area) // 删除圆形覆盖物
                    $scope.results.splice(index, 1)
                }
                // 点击左侧区域名称地图移至该区域
                $scope.selectCircle = function (index) {
                    map.setCenter($scope.results[index].area.point)
                    if (window.navigator.userAgent.indexOf('Firefox') != -1) { // 兼容火狐
                        $scope.results.forEach(function (item) {
                            item.area.hide()
                        })
                        setTimeout(function () {
                            $scope.results.forEach(function (item) {
                                item.area.show()
                            })
                        }, 0)
                    }
                }
                // 回显操作
                function recoverMap (t) {
                    circle = null
                    var point = new BMap.Point(t.longitude, t.latitude)
                    circle = new BMap.Circle(point, t.distance, {
                        strokeWeight: 2,
                        strokeColor: 'red',
                        fillColor: '#fc7878'
                    })
                    map.addOverlay(circle)
                    circle.setFillColor('#fc7878')
                    circle.disableMassClear()
                    marker = new BMap.Marker(point); // 创建标注
                    map.addOverlay(marker)
                    marker.disableMassClear()
                    $scope.results.push({
                        area: circle,
                        marker: marker,
                        latitude: circle.point.lat,
                        longitude: circle.point.lng,
                        baName: t.baName,
                        distance: t.distance
                    })
                }

                $scope.search = function (e) {
                    if (e.keyCode == '13' || e === 'a') {
                        var local = new BMap.LocalSearch(map, { // 智能搜索
                            onSearchComplete: fn
                        })
                        if ($scope.searchArea) {
                            local.search($scope.searchArea)
                        }
                    }

                    function fn () {
                        // 如果搜索的有结果
                        if (local.getResults() != undefined) {
                            if (local.getResults().getPoi(0)) {
                                point = local.getResults().getPoi(0).point; // 获取第一个智能搜索的结果
                                map.centerAndZoom(point, 10)
                            } else {
                                $rootScope.alertModel({
                                    text: '未匹配到地点',
                                    resCode: '00001'
                                })
                            }
                        } else {
                            $rootScope.alertModel({
                                text: '未找到搜索结果',
                                resCode: '00001'
                            })
                        }
                    }
                }
                $scope.initMap = function () {
                    $scope.circleList.forEach(function (t) {
                        recoverMap(t)
                    })
                }
                if ($scope.circleList && $scope.circleList.length) {
                    $scope.initMap()
                }

                $scope.submit = function (v) {
                    if (v == '1') {
                        $scope.circleList = origionList
                    } else {
                        $scope.circleList = []
                        $scope.results.forEach(function (item) {
                            $scope.circleList.push({
                                latitude: item.latitude,
                                longitude: item.longitude,
                                baName: item.baName,
                                distance: item.distance
                            })
                        })
                    }
                    $scope.close = false
                    $scope.isCircleListEmpty()
                }
            }]
        }
    })
    .directive('chooseTime', function () {
        return {
            restrict: 'E',
            templateUrl: './src/app/zzy/launchplan/setTactics/chooseTime.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {
                /*以下为时间定向弹框*/
                $scope.quickChoose = {
                    'to5': false,
                    'to11': false,
                    'to17': false,
                    'to23': false,
                    'Monday': false,
                    'Tuesday': false,
                    'Wednesday': false,
                    'Thursday': false,
                    'Friday': false,
                    'Saturday': false,
                    'Sunday': false,
                    'allDays': false
                }
                $scope.showtime = { // 在页面中显示的时间段
                    'Monday': [],
                    'Tuesday': [],
                    'Wednesday': [],
                    'Thursday': [],
                    'Friday': [],
                    'Saturday': [],
                    'Sunday': []
                }
                $scope.chosedObj = {} // 后台需要的数据格式,回显将数据赋给它即可
                $scope.showTimeLayer = false; // 整个弹框
                $scope.ifShowTimeLayer = function () { // 打开或关闭时间选择弹框
                    // $scope.showTimeLayer = !$scope.showTimeLayer
                    if ($scope.showTimeLayer === false) {
                        $scope.showTimeLayer = true
                    } else if ($scope.showTimeLayer === true) {
                        $scope.showTimeLayer = false
                        var countKey = 0
                        for (var key in $scope.chosedObj) { // 遍历$scope.chosedObj，如果没有数据则关闭弹窗时，选用默认单选按钮
                            countKey++
                        }
                        if (countKey === 0) {
                            $scope.resuleObj.time = '0'
                        }
                    }
                }
                $scope.hour1 = []; // 星期一的时间点
                $scope.hour2 = []
                $scope.hour3 = []
                $scope.hour4 = []
                $scope.hour5 = []
                $scope.hour6 = []
                $scope.hour7 = []

                // $scope.saveHour1 = []
                // $scope.saveHour2 = []
                // $scope.saveHour3 = []
                // $scope.saveHour4 = []
                // $scope.saveHour5 = []
                // $scope.saveHour6 = []
                // $scope.saveHour7 = []
                for (var i = 0; i < 24; i++) { // 生成时间点
                    $scope.hour1.push({'value': i, 'ifChosed': false})
                    $scope.hour2.push({'value': i, 'ifChosed': false})
                    $scope.hour3.push({'value': i, 'ifChosed': false})
                    $scope.hour4.push({'value': i, 'ifChosed': false})
                    $scope.hour5.push({'value': i, 'ifChosed': false})
                    $scope.hour6.push({'value': i, 'ifChosed': false})
                    $scope.hour7.push({'value': i, 'ifChosed': false})
                }
                /**数据回显 */
                $scope.backShow = function (obj) {
                    if (obj[1]) {
                        for (var k = 0; k < obj[1].length; k++) {
                            for (var n = 0; n < $scope.hour1.length; n++) {
                                if (obj[1][k] === $scope.hour1[n].value) {
                                    $scope.hour1[n].ifChosed = true
                                }
                            }
                        }
                    }
                    if (obj[2]) {
                        for (var k = 0; k < obj[2].length; k++) {
                            for (var n = 0; n < $scope.hour2.length; n++) {
                                if (obj[2][k] === $scope.hour2[n].value) {
                                    $scope.hour2[n].ifChosed = true
                                }
                            }
                        }
                    }
                    if (obj[3]) {
                        for (var k = 0; k < obj[3].length; k++) {
                            for (var n = 0; n < $scope.hour3.length; n++) {
                                if (obj[3][k] === $scope.hour3[n].value) {
                                    $scope.hour3[n].ifChosed = true
                                }
                            }
                        }
                    }
                    if (obj[4]) {
                        for (var k = 0; k < obj[4].length; k++) {
                            for (var n = 0; n < $scope.hour4.length; n++) {
                                if (obj[4][k] === $scope.hour4[n].value) {
                                    $scope.hour4[n].ifChosed = true
                                }
                            }
                        }
                    }
                    if (obj[5]) {
                        for (var k = 0; k < obj[5].length; k++) {
                            for (var n = 0; n < $scope.hour5.length; n++) {
                                if (obj[5][k] === $scope.hour5[n].value) {
                                    $scope.hour5[n].ifChosed = true
                                }
                            }
                        }
                    }
                    if (obj[6]) {
                        for (var k = 0; k < obj[6].length; k++) {
                            for (var n = 0; n < $scope.hour6.length; n++) {
                                if (obj[6][k] === $scope.hour6[n].value) {
                                    $scope.hour6[n].ifChosed = true
                                }
                            }
                        }
                    }
                    if (obj[7]) {
                        for (var k = 0; k < obj[7].length; k++) {
                            for (var n = 0; n < $scope.hour7.length; n++) {
                                if (obj[7][k] === $scope.hour7[n].value) {
                                    $scope.hour7[n].ifChosed = true
                                }
                            }
                        }
                    }
                    $scope.sureTimeChose()
                }
                /**打开弹窗，并进行回显 */
                $scope.openLayer = function () {
                    // $scope.showTimeLayer=true
                    $scope.backShow($scope.chosedObj)
                }

                /**选择时间点 */
                $scope.chooseTime = function (hour, index) { // 选择时间点
                    hour[index].ifChosed = !hour[index].ifChosed
                }
                /**时间段的快速选择 */
                $scope.chooseTimeLine = function (lasthour) { // 时间段的快速选择
                    var whichTime = ''
                    if (lasthour === 5) {
                        whichTime = $scope.quickChoose.to5
                    } else if (lasthour === 11) {
                        whichTime = $scope.quickChoose.to11
                    } else if (lasthour === 17) {
                        whichTime = $scope.quickChoose.to17
                    } else if (lasthour === 23) {
                        whichTime = $scope.quickChoose.to23
                    }
                    if (whichTime === true) {
                        for (var i = 0; i < 24; i++) {
                            if (i > lasthour - 6 && i <= lasthour) {
                                $scope.hour1[i].ifChosed = true
                                $scope.hour2[i].ifChosed = true
                                $scope.hour3[i].ifChosed = true
                                $scope.hour4[i].ifChosed = true
                                $scope.hour5[i].ifChosed = true
                                $scope.hour6[i].ifChosed = true
                                $scope.hour7[i].ifChosed = true
                            }
                        }
                    } else if (whichTime === false) {
                        for (var i = 0; i < 24; i++) {
                            if (i > lasthour - 6 && i <= lasthour) {
                                $scope.hour1[i].ifChosed = false
                                $scope.hour2[i].ifChosed = false
                                $scope.hour3[i].ifChosed = false
                                $scope.hour4[i].ifChosed = false
                                $scope.hour5[i].ifChosed = false
                                $scope.hour6[i].ifChosed = false
                                $scope.hour7[i].ifChosed = false
                            }
                        }
                    }
                }
                /**星期几的快速选择 */
                $scope.changeEveryday = function (whichday) { // 星期几的快速选择
                    var whichAllTime = ''
                    var whichWeekday = ''
                    if (whichday === 1) {
                        whichWeekday = $scope.quickChoose.Monday
                        whichAllTime = $scope.hour1
                    } else if (whichday === 2) {
                        whichWeekday = $scope.quickChoose.Tuesday
                        whichAllTime = $scope.hour2
                    } else if (whichday === 3) {
                        whichWeekday = $scope.quickChoose.Wednesday
                        whichAllTime = $scope.hour3
                    } else if (whichday === 4) {
                        whichWeekday = $scope.quickChoose.Thursday
                        whichAllTime = $scope.hour4
                    } else if (whichday === 5) {
                        whichWeekday = $scope.quickChoose.Friday
                        whichAllTime = $scope.hour5
                    } else if (whichday === 6) {
                        whichWeekday = $scope.quickChoose.Saturday
                        whichAllTime = $scope.hour6
                    } else if (whichday === 7) {
                        whichWeekday = $scope.quickChoose.Sunday
                        whichAllTime = $scope.hour7
                    }

                    if (whichWeekday === true) {
                        for (var i = 0; i < 24; i++) {
                            whichAllTime[i].ifChosed = true
                        }
                    } else if (whichWeekday === false) {
                        for (var i = 0; i < 24; i++) {
                            whichAllTime[i].ifChosed = false
                        }
                    }
                }
                /**全部取消 */
                $scope.cancelAll = function () { // 全部取消
                    $scope.quickChoose.Monday = false
                    $scope.quickChoose.Tuesday = false
                    $scope.quickChoose.Wednesday = false
                    $scope.quickChoose.Thursday = false
                    $scope.quickChoose.Friday = false
                    $scope.quickChoose.Saturday = false
                    $scope.quickChoose.Sunday = false
                    $scope.quickChoose.to5 = false
                    $scope.quickChoose.to11 = false
                    $scope.quickChoose.to17 = false
                    $scope.quickChoose.to23 = false
                    $scope.quickChoose.allDays = false
                    for (var i = 0; i < 24; i++) {
                        $scope.hour1[i].ifChosed = false
                        $scope.hour2[i].ifChosed = false
                        $scope.hour3[i].ifChosed = false
                        $scope.hour4[i].ifChosed = false
                        $scope.hour5[i].ifChosed = false
                        $scope.hour6[i].ifChosed = false
                        $scope.hour7[i].ifChosed = false
                    }
                }
                /**全选功能 */
                $scope.chooseAllTime = function () { // 全选功能
                    if ($scope.quickChoose.allDays === true) {
                        // console.log('true')
                        $scope.quickChoose.Monday = true
                        $scope.quickChoose.Tuesday = true
                        $scope.quickChoose.Wednesday = true
                        $scope.quickChoose.Thursday = true
                        $scope.quickChoose.Friday = true
                        $scope.quickChoose.Saturday = true
                        $scope.quickChoose.Sunday = true
                        $scope.quickChoose.to5 = true
                        $scope.quickChoose.to11 = true
                        $scope.quickChoose.to17 = true
                        $scope.quickChoose.to23 = true
                        for (var i = 0; i < 24; i++) {
                            $scope.hour1[i].ifChosed = true
                            $scope.hour2[i].ifChosed = true
                            $scope.hour3[i].ifChosed = true
                            $scope.hour4[i].ifChosed = true
                            $scope.hour5[i].ifChosed = true
                            $scope.hour6[i].ifChosed = true
                            $scope.hour7[i].ifChosed = true
                        }
                    } else if ($scope.quickChoose.allDays === false) {
                        // console.log('false')
                        $scope.cancelAll()
                    }
                }
                $scope.cancelBtn = function () { // 取消按钮功能
                    $scope.cancelAll()
                    // if($scope.saveHour1.length>0 || $scope.saveHour2.length>0||$scope.saveHour3.length>0||$scope.saveHour4.length>0||$scope.saveHour5.length>0||$scope.saveHour6.length>0||$scope.saveHour7.length>0){
                    //   $scope.hour1 = angular.copy($scope.saveHour1)
                    //   $scope.hour2 = angular.copy($scope.saveHour2)
                    //   $scope.hour3 = angular.copy($scope.saveHour3)
                    //   $scope.hour4 = angular.copy($scope.saveHour4)
                    //   $scope.hour5 = angular.copy($scope.saveHour5)
                    //   $scope.hour6 = angular.copy($scope.saveHour6)
                    //   $scope.hour7 = angular.copy($scope.saveHour7)
                    // }

                    $scope.ifShowTimeLayer()
                }

                /* 此方法可将相连的时间点组成时间段 */
                $scope.groupTime = function (group, chosedArr) {
                    // var group1 = [];    //分组
                    var item = {}; // 一组，成分为start和end,代表了连续的首和尾
                    for (var m = 0; m < chosedArr.length; m++) {
                        if (m === 0) { // 将第一个值直接赋给第一个item的start属性
                            item.start = chosedArr[0]
                        }
                        if (m > 0 && chosedArr[m] - chosedArr[m - 1] !== 1) { // 如果不连续了，则将连续的最后一个值（即上一个值）赋给item的end属性，将此时的值赋给下一个item的start属性
                            item.end = chosedArr[m - 1]
                            group.push(angular.copy(item))
                            item = {}
                            item.start = chosedArr[m]
                        }
                        if (m + 1 === chosedArr.length) { // 最后一个直接赋给最后的item的end属性
                            item.end = chosedArr[m]
                            group.push(angular.copy(item))
                        }
                    }
                }
                /**确定选择，并生成提交后台的数据和展示页面的时间段数据 */
                $scope.sureTimeChose = function () {
                    $scope.chosedObj = {}
                    var chosedArr1 = []
                    var chosedArr2 = []
                    var chosedArr3 = []
                    var chosedArr4 = []
                    var chosedArr5 = []
                    var chosedArr6 = []
                    var chosedArr7 = []
                    for (var i = 0; i < 24; i++) {
                        if ($scope.hour1[i].ifChosed === true) {
                            chosedArr1.push($scope.hour1[i].value)
                        }
                        if ($scope.hour2[i].ifChosed === true) {
                            chosedArr2.push($scope.hour2[i].value)
                        }
                        if ($scope.hour3[i].ifChosed === true) {
                            chosedArr3.push($scope.hour3[i].value)
                        }
                        if ($scope.hour4[i].ifChosed === true) {
                            chosedArr4.push($scope.hour4[i].value)
                        }
                        if ($scope.hour5[i].ifChosed === true) {
                            chosedArr5.push($scope.hour5[i].value)
                        }
                        if ($scope.hour6[i].ifChosed === true) {
                            chosedArr6.push($scope.hour6[i].value)
                        }
                        if ($scope.hour7[i].ifChosed === true) {
                            chosedArr7.push($scope.hour7[i].value)
                        }
                    }
                    // console.log(chosedArr1)
                    // 将选中的时间点存入$scope.chosedObj这个对象中
                    if (chosedArr1.length > 0) {
                        $scope.chosedObj[1] = angular.copy(chosedArr1)
                    }
                    if (chosedArr2.length > 0) {
                        $scope.chosedObj[2] = angular.copy(chosedArr2)
                    }
                    if (chosedArr3.length > 0) {
                        $scope.chosedObj[3] = angular.copy(chosedArr3)
                    }
                    if (chosedArr4.length > 0) {
                        $scope.chosedObj[4] = angular.copy(chosedArr4)
                    }
                    if (chosedArr5.length > 0) {
                        $scope.chosedObj[5] = angular.copy(chosedArr5)
                    }
                    if (chosedArr6.length > 0) {
                        $scope.chosedObj[6] = angular.copy(chosedArr6)
                    }
                    if (chosedArr7.length > 0) {
                        $scope.chosedObj[7] = angular.copy(chosedArr7)
                    }

                    var group1 = []
                    var group2 = []
                    var group3 = []
                    var group4 = []
                    var group5 = []
                    var group6 = []
                    var group7 = []

                    $scope.groupTime(group1, chosedArr1)
                    $scope.groupTime(group2, chosedArr2)
                    $scope.groupTime(group3, chosedArr3)
                    $scope.groupTime(group4, chosedArr4)
                    $scope.groupTime(group5, chosedArr5)
                    $scope.groupTime(group6, chosedArr6)
                    $scope.groupTime(group7, chosedArr7)
                    // $scope.groupTime($scope.showtime.Monday, chosedArr1)
                    // $scope.groupTime($scope.showtime.Tuesday, chosedArr2)
                    // $scope.groupTime($scope.showtime.Wednesday, chosedArr3)
                    // $scope.groupTime($scope.showtime.Thursday, chosedArr4)
                    // $scope.groupTime($scope.showtime.Friday, chosedArr5)
                    // $scope.groupTime($scope.showtime.Saturday, chosedArr6)
                    // $scope.groupTime($scope.showtime.Sunday, chosedArr7)
                    $scope.showtime.Monday = group1
                    $scope.showtime.Tuesday = group2
                    $scope.showtime.Wednesday = group3
                    $scope.showtime.Thursday = group4
                    $scope.showtime.Friday = group5
                    $scope.showtime.Saturday = group6
                    $scope.showtime.Sunday = group7
                    // console.log($scope.showtime.Monday)
                    /**将本次的操作保存，下次打开弹窗回显 */
                    // $scope.saveHour1 = angular.copy($scope.hour1)
                    // $scope.saveHour2 = angular.copy($scope.hour2)
                    // $scope.saveHour3 = angular.copy($scope.hour3)
                    // $scope.saveHour4 = angular.copy($scope.hour4)
                    // $scope.saveHour5 = angular.copy($scope.hour5)
                    // $scope.saveHour6 = angular.copy($scope.hour6)
                    // $scope.saveHour7 = angular.copy($scope.hour7)
                    $scope.ifShowTimeLayer()
                    // console.log( $scope.chosedObj)
                }
            }]
        }
    })
    /*行业选择弹框，本期暂不做，勿删 */
    // .directive('chooseIndustry', function () {
    //   return {
    //     restrict: 'E',
    //     templateUrl: "./src/app/extensionPlan/setTactics/chooseIndustry.html?v=" + v,
    //     controller: ["$scope", 'ajaxRquest', function ($scope, ajaxRquest) {

    //     }]
    //   }
    // })
    .directive('chooseIp', function () {
        return {
            restrict: 'E',
            templateUrl: './src/app/zzy/launchplan/setTactics/chooseIp.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {
                /*黑白名单*/
                $scope.whiteList = ''; // 白名单数据
                $scope.blackList = ''; // 黑名单数据
                $scope.whiteLists = ''; // 白名单处理后的数据
                $scope.blackLists = ''; // 黑名单处理后的数据
                $scope.ipListBox = false; // 控制弹框是否显示
                $scope.whiteIpText = false; // 白名单文本框是否显示
                $scope.blackIpText = false; // 黑名单文本框是否显示
                $scope.whiteEndData = ''; // 白名单保存后数据
                $scope.blackEndData = ''; // 黑名单保存后数据
                $scope.whiteBackData = ''; // 白名单回显后数据
                $scope.blackBackData = ''; // 黑名单回显后数据
                $scope.chooseWhiteIpList = function () { // 选择白名单
                    $scope.ipListBox = true
                    $scope.whiteIpText = true
                    $scope.blackIpText = false
                    $scope.whiteBackData = $scope.whiteList; // 白名单回显后数据传给回显变量
                    $scope.whiteEndData = $scope.whiteBackData; // 白名单回显变量传给保存后数据
                }
                $scope.chooseBlackIpList = function () { // 选择黑名单
                    $scope.ipListBox = true
                    $scope.blackIpText = true
                    $scope.whiteIpText = false
                    $scope.blackBackData = $scope.blackList; // 黑名单回显后数据后数据传给回显变量
                    $scope.blackEndData = $scope.blackBackData; // 黑名白名单回显变量传给保存后数据
                }
                $scope.close = function () { // 关闭弹框
                    $scope.ipListBox = false
                    console.log($scope.whiteList)
                    console.log($scope.whiteEndData)
                    $scope.whiteList = $scope.whiteEndData; // 白名单数据回显
                    $scope.blackList = $scope.blackEndData; // 黑名单数据回显
                }
                $scope.isValidIP = function (ip) { // 验证ip正则表达式
                    var reg = /^(?:(?:2[0-4][0-9]\.)|(?:25[0-5]\.)|(?:1[0-9][0-9]\.)|(?:[1-9][0-9]\.)|(?:[0-9]\.)){3}(?:(?:2[0-5][0-5])|(?:25[0-5])|(?:1[0-9][0-9])|(?:[1-9][0-9])|(?:[0-9]))$/
                    return reg.test(ip)
                }
                $scope.RegList = function () { // 处理文本框的数据并且去空
                    $scope.whiteReg = false
                    $scope.blackReg = false
                    if ($scope.whiteLists != $scope.whiteList) {
                        $scope.whiteLists = $scope.whiteList.split('\n')
                        for (var i = 0; i < $scope.whiteLists.length; i++) {
                            if ($scope.whiteLists[i] == '' || $scope.whiteLists[i] == undefined) {
                                $scope.whiteLists.splice(i, 1)
                                i = i - 1
                                if ($scope.isValidIP($scope.whiteLists[i]) == false) {
                                    $scope.whiteReg = true
                                }
                            } else {
                                if ($scope.isValidIP($scope.whiteLists[i]) == false) {
                                    $scope.whiteReg = true
                                }
                            }
                        }
                    }
                    if ($scope.blackLists != $scope.blackList) {
                        $scope.blackLists = $scope.blackList.split('\n')
                        for (var i = 0; i < $scope.blackLists.length; i++) {
                            if ($scope.blackLists[i] == '' || $scope.blackLists[i] == undefined) {
                                $scope.blackLists.splice(i, 1)
                                i = i - 1
                                if ($scope.isValidIP($scope.blackLists[i]) == false) {
                                    $scope.blackReg = true
                                }
                            } else {
                                if ($scope.isValidIP($scope.blackLists[i]) == false) {
                                    $scope.blackReg = true
                                }
                            }
                        }
                    }
                }

                $scope.keyUpWhite = function (e) { // 监听白名单键盘事件并判断输入是否符合规则
                    var keycode = window.event ? e.keyCode : e.which
                    $scope.whiteList = $scope.whiteList.replace(/[\r\n]+/g, '\n'); // 去空格
                    if (keycode == 13) {
                        $scope.RegList()
                        if ($scope.whiteLists == '' || $scope.whiteLists == undefined) {
                            $scope.alertModel({
                                text: 'IP地址不能为空', // 内容
                                resCode: '00001'
                            })
                            return false
                        }
                        if ($scope.whiteReg || $scope.isValidIP($scope.whiteLists[0]) == false) {
                            $scope.alertModel({
                                text: 'IP地址格式不正确', // 内容
                                resCode: '00001'
                            })
                        }
                    }
                }
                $scope.keyUpBlack = function (e) { // 监听黑名单键盘事件并判断输入是否符合规则
                    var keycode = window.event ? e.keyCode : e.which
                    $scope.blackList = $scope.blackList.replace(/[\r\n]+/g, '\n'); // 去空格
                    if (keycode == 13) {
                        $scope.RegList()
                        if ($scope.blackLists == '' || $scope.blackLists == undefined) {
                            $scope.alertModel({
                                text: 'IP地址不能为空', // 内容
                                resCode: '00001'
                            })
                            return false
                        }
                        if ($scope.blackReg || $scope.isValidIP($scope.blackLists[0]) == false) {
                            $scope.alertModel({
                                text: 'IP地址格式不正确', // 内容
                                resCode: '00001'
                            })
                        }
                    }
                }
                $scope.addIpList = function () { // 提交数据并再次验证是否正确
                    /*黑名单 验证*/
                    $scope.RegList()
                    if ($scope.blackIpText) {
                        console.log('黑名单')
                        if ($scope.blackLists == '' || $scope.blackLists == undefined) {
                            $scope.resuleObj.IPlist=0;
                            $scope.ipListBox = false
                        } else if ($scope.blackReg || $scope.isValidIP($scope.blackLists[0]) == false) {
                            $scope.alertModel({
                                text: 'IP地址格式不正确', // 内容
                                resCode: '00001'
                            })
                            return false
                        } else {
                            $scope.ipListBox = false
                            console.log($scope.blackList)
                            $scope.fullBlack = $scope.blackLists
                            $scope.blackEndData = $scope.blackList
                        }
                    }
                    /*白名单验证*/
                    if ($scope.whiteIpText) {
                        if ($scope.whiteLists == '' || $scope.whiteLists == undefined) {
                            $scope.resuleObj.IPlist=0;
                            $scope.ipListBox = false
                            return false
                        } else if ($scope.whiteReg || $scope.isValidIP($scope.whiteLists[0]) == false) {
                            $scope.alertModel({
                                text: 'IP地址格式不正确', // 内容
                                resCode: '00001'
                            })
                            return false
                        } else {
                            $scope.ipListBox = false
                            console.log($scope.whiteList)
                            $scope.fullWhite = $scope.whiteLists
                            $scope.whiteEndData = $scope.whiteList
                        }
                    }
                }
            }]
        }
    })
    .directive('chooseGroup', function () {
        return {
            restrict: 'E',
            templateUrl: './src/app/zzy/launchplan/setTactics/chooseGroup.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {
                $scope.dataList = [
                    {
                        'id': '10010',
                        'text': '地区',
                        'ifShowChildren': false,
                        'ifChosed': false,
                        'region_type': '0',
                        'enable': 'N',
                        'childrenList': [{
                            'parentId': '10010',
                            'id': '10011',
                            'text': '上海',
                            'ifShowChildren': false,
                            'ifChosed': false,
                            'region_type': '0',
                            'enable': 'Y',
                            'childrenList': [{
                                'parentId': '10011',
                                'id': '10035',
                                'text': '徐汇区',
                                'ifShowChildren': false,
                                'ifChosed': false,
                                'region_type': '1',
                                'enable': 'Y'
                            }, {
                                'parentId': '10011',
                                'id': '10036',
                                'text': '松江区',
                                'ifShowChildren': false,
                                'ifChosed': false,
                                'region_type': '1',
                                'enable': 'Y'
                            }]
                        }, {
                            'parentId': '10010',
                            'id': '10022',
                            'text': '北京',
                            'ifShowChildren': false,
                            'ifChosed': false,
                            'region_type': '0',
                            'enable': 'Y',
                            'childrenList': [{
                                'parentId': '10022',
                                'id': '10028',
                                'text': '朝阳区',
                                'ifShowChildren': false,
                                'ifChosed': false,
                                'region_type': '1',
                                'enable': 'Y'
                            }, {
                                'parentId': '10022',
                                'id': '10029',
                                'text': '长安区',
                                'ifShowChildren': false,
                                'ifChosed': false,
                                'region_type': '1',
                                'enable': 'Y'
                            }]
                        }]
                    },
                    {
                        'id': '10020',
                        'text': '性别',
                        'ifShowChildren': false,
                        'ifChosed': false,
                        'region_type': '0',
                        'enable': 'N',
                        'childrenList': [{
                            'parentId': '10020',
                            'id': '10012',
                            'text': '男士',
                            'ifShowChildren': false,
                            'ifChosed': false,
                            'region_type': '1',
                            'enable': 'Y'
                        }, {
                            'parentId': '10020',
                            'id': '10012',
                            'text': '女士',
                            'ifShowChildren': false,
                            'ifChosed': false,
                            'region_type': '1',
                            'enable': 'Y'
                        }]
                    }
                ]

                /**获取兴趣人群,人群定向查询接口 - 张新强 */
                $scope.getInterestGroups = function (selfList) {
                    
                    $.ajax({
                        url : $rootScope.app.project_name+'/zzyLaunchPlan/getInterestGroups',
                        data: {
                            parentId: selfList ? selfList.id : 'a2126' // 标签编号  是
                        }
                    }).then(function (res) {
                        if (res.httpCode == 200) {
                            $scope.$apply(function () {
                                for (var i = 0; i < res.data.length; i++) {
                                    res.data[i].ifShowChildren = false
                                    res.data[i].ifChosed = false
                                }
                                if (selfList) {
                                    selfList.childrenList = res.data
                                } else {
                                    $scope.dataList = res.data
                                }
                            })
                        } else {
                            $scope.alertModal({"content":"系统异常"});
                        }
                    })
                }
                $scope.getInterestGroups()
                // 展开功能
                $scope.showChildren = function (list) {
                    list.ifShowChildren = !list.ifShowChildren
                    if (!list.childrenList) {
                        $scope.getInterestGroups(list)
                    }
                }

                /**打开或关闭兴趣弹框 */
                $scope.showGroupLayer = false
                $scope.ifShowGroupLayer = function () { // 打开或关闭兴趣弹框
                    $scope.clearAll()
                    if ($scope.showGroupLayer === false) {
                        $scope.showGroupLayer = true
                        $scope.getInterestGroups()
                        $scope.changeChosedList()
                    } else if ($scope.showGroupLayer === true) {
                        $scope.showGroupLayer = false
                        if ($scope.chosedList.length === 0) { // 判断是否已选数据，如果没有，则关闭按钮时选用默认单选按钮
                            $scope.resuleObj.group = '0'
                        }
                    }
                    // $scope.showGroupLayer = !$scope.showGroupLayer
                }
                $scope.chosedData = {} // 选中的人群，对象格式
                $scope.chosedList = [] // 提交后台的最终数据,回显数据也存放这里
                $scope.showChosedList = [] // 页面展示的数据
                $scope.giveServer = [] // 回显数据也存放这里
                $scope.finally = {} // 每条数据中每一个大类的集合，包含类名，中文名，id，对象格式
                $scope.finallyArr = [] // 一条数据，包含所有大类

                /*** 选中状态更改,list-本身，pList-父级，gpList-父父级，ggpList-父父父级*/
                $scope.chooseAction = function (list, pList, gpList, ggpList) {
                    list.ifChosed = !list.ifChosed
                    if (pList) { // 判断有没有父级
                        if (pList.enable === 'N') { // 判断父级有没有不可选的标题
                            if (!$scope.chosedData[pList.text]) { // 初始化$scope.chosedData，将该键对应的值初始化为数组
                                $scope.chosedData[pList.text] = []
                            }
                            if (list.ifChosed === true) { // 如果选中，将本身放入$scope.chosedData[pList.text]中
                                list.titleMetre = pList.text
                                $scope.chosedData[pList.text].push(list)
                            }
                            if (list.ifChosed === false) {
                                $scope.chosedData[pList.text].remove(list)
                            }
                        } else {
                            if (gpList) { // 判断有没有父父级
                                if (gpList.enable === 'N') {
                                    if (!$scope.chosedData[gpList.text]) {
                                        $scope.chosedData[gpList.text] = []
                                    }
                                    if (list.ifChosed === true) {
                                        list.titleMetre = gpList.text
                                        $scope.chosedData[gpList.text].push(list)
                                    }
                                    if (list.ifChosed === false) {
                                        $scope.chosedData[gpList.text].remove(list)
                                    }
                                } else {
                                    if (ggpList) {
                                        if (ggpList.enable === 'N') {
                                            if (!$scope.chosedData[ggpList.text]) {
                                                $scope.chosedData[ggpList.text] = []
                                            }
                                            if (list.ifChosed === true) {
                                                list.titleMetre = ggpList.text
                                                $scope.chosedData[ggpList.text].push(list)
                                            }
                                            if (list.ifChosed === false) {
                                                $scope.chosedData[ggpList.text].remove(list)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    $scope.createFinallyArr()
                }
                /**创建一条包含所有大类的数据 */
                $scope.createFinallyArr = function () {
                    $scope.finallyArr = []
                    for (var key in $scope.chosedData) { // 遍历$scope.chosedData={}  （选中的人群，对象格式）
                        // console.log($scope.chosedData[key])
                        var finallyObj = {}
                        if ($scope.chosedData[key].length === 0) {
                            break
                        }
                        var name = ''
                        var id = ''
                        var titleText = ''
                        for (var i = 0; i < $scope.chosedData[key].length; i++) {
                            name += $scope.chosedData[key][i].text + ' OR '
                            id += $scope.chosedData[key][i].id + ' OR '
                        }
                        finallyObj.titleText = key
                        finallyObj.allName = name.substr(0, name.length - 3)
                        finallyObj.allId = id.substr(0, id.length - 3)
                        $scope.finallyArr.push(finallyObj)
                    }
                }
                /**右框清除功能 */
                $scope.clearAll = function () {
                    $scope.chosedData = {}
                    $scope.getInterestGroups()
                    // $scope.chosedList=[]
                    // $scope.chosedList=angular.copy($scope.giveServer)
                }
                /**下框的删除 */
                $scope.deleteThis = function (list, index) {
                    $scope.showChosedList.remove(list)
                    $scope.chosedList.remove($scope.chosedList[index])
                }
                /**保存功能 */
                $scope.sureEvent = function () {
                    // $scope.chosedList=[]
                    // $scope.chosedList=angular.copy($scope.giveServer)
                    $scope.createFinallyArr()
                    // console.log($scope.finallyArr)
                    if ($scope.finallyArr.length > 0) { // 已选择数据才会往$scope.chosedList中插入数据
                        $scope.chosedList.push($scope.finallyArr)
                    }
                    $scope.ifShowGroupLayer()
                    $scope.changeChosedList()
                }
                /**将数据转换成在页面展示的格式，如（）and（） */
                $scope.changeChosedList = function () {
                    var emptyArr = []
                    for (var i = 0; i < $scope.chosedList.length; i++) {
                        var str = ''
                        for (var m = 0; m < $scope.chosedList[i].length; m++) {
                            str += '(' + $scope.chosedList[i][m].allName + ')' + 'and'
                        }
                        str = str.substr(0, str.length - 3)
                        emptyArr.push(str)
                    }
                    $scope.showChosedList = angular.copy(emptyArr)
                }
            }]
        }
    })
    .directive('chooseMedia', function () {
        return {
            restrict: 'E',
            scope: {
                showAdsList: '=adsList',
                showPackageWindow: '=showPackage',
                isShowAdsListEmpty: '&'
            },
            templateUrl: './src/app/zzy/launchplan/setTactics/chooseMedia.html?v=' + v,
            controller: ['$rootScope', '$scope', '$http', '$state','$timeout', function ($rootScope, $scope, $http, $state,$timeout) {

                // 场景包广告位分页
                $scope.pagingData = {
                    'total': 2,
                    'currentPage': '1',
                    'paginLength': 6,
                    'pageSize': '10'
                };
                // 查询流量场景包接口
                $scope.queryPackInterface = function () {
                    $.ajax({
                        url : $rootScope.app.project_name+'/zzyLaunchPlan/getScenesPackagePrev',
                        data: {
                            adPlanId: $state.params.adPlanId, // long  广告主id  是
                            scenesName: $scope.scenesName || '',
                            current: '', // int  当前页码  否
                            pageSize: '' // int  每页条数  否
                        }
                    }).then(function (res) {
                        console.log(res);
                        $scope.$apply(function () {
                            $scope.copyQueryPack( res.data.list);
                            $scope.pagingData.total=res.data.total;
                            onoff = false;
                        })
                    })
                }
                $scope.queryPackInterface()

                // 根据场景包id 获取到广告位
                $scope.choosePageAds = function (item, index) {
                    $.ajax({
                        url : $rootScope.app.project_name+'/zzyLaunchPlan/getToolManageCrtDelit',
                        data: {
                            id: item.id // 场景id
                        }
                    }).then(function (res) {
                        console.log(res);
                        $scope.$apply(function () {
                            item.isChecked = !item.isChecked
                            $scope.adsPackageList = res.data.records;
                            $scope.copyChooseAds(item.id)
                        })
                    })
                }
                $scope.displayList = [];

                // copy场景包数据
                $scope.copyQueryPack = function (list) {
                    var obj
                    for (var i = 0; i < list.length; i++) {
                        obj = {};
                        obj.id = list[i].id;
                        obj.scenesName = list[i].scenesName;
                        obj.scenesType = list[i].scenesType;
                        obj.isChecked = false;
                        $scope.displayList.push(obj)
                    }
                    $scope.checkSelected()
                };

                // copy 已选择广告位数据
                $scope.copyChooseAds = function (id) {
                    $scope.chooseAdsList = []
                    var obj
                    for (var i = 0; i < $scope.adsPackageList.length; i++) {
                        obj = {}
                        obj.id = $scope.adsPackageList[i].id
                        obj.slotName = $scope.adsPackageList[i].slotName
                        obj.platformId = $scope.adsPackageList[i].platformId
                        obj.parentId = id   // 场景包id
                        $scope.chooseAdsList.push(obj)
                    }
                    $scope.showAdsList = $scope.showAdsList.concat($scope.chooseAdsList)
                    // 数组去重
                    var hash = {}
                    $scope.showAdsList = $scope.showAdsList.reduce(function (item, next) {
                        hash[next.id] ? '' : hash[next.id] = true && item.push(next)
                        return item
                    }, [])
                    console.log($scope.showAdsList)
                }
                // 已选择的场景包
                $scope.changePackage = function (item) {
                    if (!item.isChecked) {
                         $scope.choosePageAds(item)
                    } else {
                        item.isChecked=!item.isChecked
                        $scope.showAdsList = $scope.showAdsList.filter(function (t) {
                            return item.id!=t.parentId
                        })
                    }
                }
                //  判断是否选中场景流量包
                $scope.checkSelected = function(){
                    function isEqual(id){
                        return $scope.showAdsList.some(function(val){
                            return id == val.parentId
                        })
                    }
                    $scope.displayList.forEach(function(item){
                        item.isChecked = isEqual(item.id)
                    })
                }

                // 删除已选择的广告位
                $scope.deleteAds = function (item, index1) {
                    $scope.showAdsList.splice(index1, 1)
                    $scope.checkSelected()
                }

                // 确定选择的广告位
                $scope.chooseList = function () {
                    $scope.showPackageWindow = false
                    $scope.isShowAdsListEmpty()
                }
                // 关闭
                $scope.closeShow = function () {
                    $scope.showAdsList = copyAdsList
                    // $timeout(function(){
                    $scope.isShowAdsListEmpty()
                    // },1000)
                    $scope.showPackageWindow = false
                }
                if ($scope.showAdsList) {
                    var copyAdsList = JSON.parse(JSON.stringify($scope.showAdsList))
                }

                var onoff = false;
                // 滚动条下拉分页获取数据
                var top = document.querySelector('#top')
                var elementTop = angular.element(top)
                console.log(elementTop)
                elementTop.scroll(function () {
                    var scrollNum = elementTop.scrollTop() // 滚动条滚动距离
                    var scrollH = elementTop[0].scrollHeight; // 滚动条高度
                    var offsetH = elementTop[0].offsetHeight;  // 可视高度

                    if (scrollNum + offsetH == scrollH && !onoff) {
                        onoff = true
                        console.log(Math.ceil($scope.pagingData.total / $scope.pagingData.pageSize))
                        if ($scope.pagingData.currentPage == Math.ceil($scope.pagingData.total / $scope.pagingData.pageSize)) {

                        } else {
                            $scope.pagingData.currentPage++
                            $scope.queryPackInterface()
                        }
                    }
                })
            }]
        }
    })
    .controller('setTacticsController', ['$rootScope', '$scope', '$http', '$state', '$timeout',function ($rootScope, $scope, $http, $state,$timeout) {
        Array.prototype.remove = function (val) {
            var index = this.indexOf(val);
            if (index > -1) {
                this.splice(index, 1);
            }
        }
        $scope.planName = $state.params.planName
        $scope.planId = $state.params.adPlanId
        $scope.budgetType = $state.params.budgetType // $state.params.budgetType
        $scope.resuleObj = {
            'time': '0', // 控制投放时段单选的值，0-不限，1-自定义
            'timeArr': [],
            'package': '0', // 控制场景流量包单选的值，0-不限，1-自定义
            'packageArr': [],
            'industry': '0', // 控制选择行业单选的值，0-不限，1-自定义
            'industryArr': [],
            'area': '0', // 控制区域定向单选的值，0-不限，1-行政区域，2-商圈
            'areaArr': [],
            'IPlist': '0', // 控制设置IP单选的值，0-不限，1-白名单，2-黑名单
            'IPlistArr': [],
            'operator': '', // 选择运营商的字符串集合，例：'A,B,C'，传给后台的数据，回显数据也赋给它
            'operatorArr': [], // 选择运营商的数组集合，例：[a,b,c]
            'machine': '', // 选择设备的字符串集合，例：'A,B,C'，传给后台的数据，回显数据也赋给它
            'machineArr': [], // 选择设备的数组集合，例：[a,b,c]
            'Lines': '', // 选择网络的字符串集合，例：'A,B,C'，传给后台的数据，回显数据也赋给它
            'allLineArr': [], // 选择网络的数组集合，例：[a,b,c]
            'group': '0', // 控制兴趣人群单选的值，0-不限，1-自定义
            'groupArr': [],
            'everydayMoney': true, // 控制每日投放预算的不限的checkbox的状态
            'everydayMoneyInput': '', // 每日投放预算
            'allMoney': true, // 控制总投放预算的不限的checkbox的状态
            'allMoneyInput': '', // 总投放预算
            'allPublic': true, // 控制总曝光数的不限的checkbox的状态
            'allPublicInput': '', // 总曝光数
            'allClick': true, // 控制总点击数的不限的checkbox的状态
            'allClickInput': '', // 总点击数
            'dayCount': true, // 控制每日投放频次的不限的checkbox的状态
            'dayCountInput': '', // 每日投放频次
            'hourCount': true, // 控制每小时投放频次的不限的checkbox的状态
            'hourCountInput': '', // 每小时投放频次数
            'showAdNum': ''
        }
        /**运营商选择 */
        $scope.checkboxListOperator = [
            {'count': '0','id': 'Operator0','name': '不限','ifchosed': true},
            {'count': '1','id': 'Operator1','name': '移动','ifchosed': false},
            {'count': '2','id': 'Operator2','name': '联通','ifchosed': false},
            {'count': '3','id': 'Operator3','name': '电信','ifchosed': false},
            {'count': '4','id': 'Operator4','name': '铁通','ifchosed': false}
        ]
        /**设备选择 */
        $scope.checkboxListMachine = [
            {'count': '0','id': 'Machine0','name': '不限','ifchosed': true},
            {'count': '1','id': 'Machine1','name': 'iphone','ifchosed': false},
            {'count': '2','id': 'Machine2','name': 'android','ifchosed': false},
            {'count': '3','id': 'Machine3','name': 'ipad','ifchosed': false}
        ]
        /**网络选择 */
        $scope.checkboxListLine = [
            {'count': '0','id': 'Line0','name': '不限','ifchosed': true},
            {'count': '1','id': 'Line1','name': 'WIFI','ifchosed': false},
            {'count': '2','id': 'Line2','name': ' 蜂窝-2G','ifchosed': false},
            {'count': '3','id': 'Line3','name': '蜂窝-3G','ifchosed': false},
            {'count': '4','id': 'Line4','name': '蜂窝-4G','ifchosed': false}
        ]
        /**选择运营商 */
        $scope.choseOperator = function (item) { // 选择运营商
            // console.log(item.ifchosed)
            $scope.resuleObj.operatorArr = []
            $scope.resuleObj.operator = ''
            if (item.count === '0') { // 如果选中不限，则其它选项取消选中
                if (item.ifchosed === true) {
                    for (var i = 1;i < $scope.checkboxListOperator.length;i++) {
                        $scope.checkboxListOperator[i].ifchosed = false
                    }
                }
            }
            if (item.count !== '0') { // 如果有其它选项，则不限选项取消选中
                $scope.checkboxListOperator[0].ifchosed = false
            }
            for (var i = 0;i < $scope.checkboxListOperator.length;i++) { // 将选中的count加入到operatorArr数组中
                if ($scope.checkboxListOperator[i].ifchosed === true) {
                    $scope.resuleObj.operatorArr.push($scope.checkboxListOperator[i].count)
                }
            }
            if ($scope.resuleObj.operatorArr.length === 0) { // 如果没有其它选项，则默认选中不限
                $scope.checkboxListOperator[0].ifchosed = true
                $scope.resuleObj.operatorArr.push($scope.checkboxListOperator[0].count)
            }
            for (var i = 0;i < $scope.resuleObj.operatorArr.length;i++) { // 制作传给后台的数据格式
                $scope.resuleObj.operator += $scope.resuleObj.operatorArr[i] + ','
            }
            $scope.resuleObj.operator = $scope.resuleObj.operator.substr(0, $scope.resuleObj.operator.length - 1)
            // console.log($scope.resuleObj.operator)
        }
        /** 选择设备*/
        $scope.choseMachine = function (item) { // 选择设备
            // console.log(item.ifchosed)
            $scope.resuleObj.machineArr = []
            $scope.resuleObj.machine = ''
            if (item.count === '0') {
                if (item.ifchosed === true) {
                    for (var i = 1;i < $scope.checkboxListMachine.length;i++) {
                        $scope.checkboxListMachine[i].ifchosed = false
                    }
                }
            }
            if (item.count !== '0') {
                $scope.checkboxListMachine[0].ifchosed = false
            }
            for (var i = 0;i < $scope.checkboxListMachine.length;i++) {
                if ($scope.checkboxListMachine[i].ifchosed === true) {
                    $scope.resuleObj.machineArr.push($scope.checkboxListMachine[i].count)
                }
            }
            if ($scope.resuleObj.machineArr.length === 0) {
                $scope.checkboxListMachine[0].ifchosed = true
                $scope.resuleObj.machineArr.push($scope.checkboxListMachine[0].count)
            }
            for (var i = 0;i < $scope.resuleObj.machineArr.length;i++) {
                $scope.resuleObj.machine += $scope.resuleObj.machineArr[i] + ','
            }
            $scope.resuleObj.machine = $scope.resuleObj.machine.substr(0, $scope.resuleObj.machine.length - 1)
            // console.log($scope.resuleObj.machine)
        }
        /**选择网络 */
        $scope.choseLines = function (item) { // 选择网络
            // console.log(item.ifchosed)
            $scope.resuleObj.allLineArr = []
            $scope.resuleObj.Lines = ''
            if (item.count === '0') {
                if (item.ifchosed === true) {
                    for (var i = 1;i < $scope.checkboxListLine.length;i++) {
                        $scope.checkboxListLine[i].ifchosed = false
                    }
                }
            }
            if (item.count !== '0') {
                $scope.checkboxListLine[0].ifchosed = false
            }
            for (var i = 0;i < $scope.checkboxListLine.length;i++) {
                if ($scope.checkboxListLine[i].ifchosed === true) {
                    $scope.resuleObj.allLineArr.push($scope.checkboxListLine[i].count)
                }
            }
            if ($scope.resuleObj.allLineArr.length === 0) {
                $scope.checkboxListLine[0].ifchosed = true
                $scope.resuleObj.allLineArr.push($scope.checkboxListLine[0].count)
            }
            for (var i = 0;i < $scope.resuleObj.allLineArr.length;i++) {
                $scope.resuleObj.Lines += $scope.resuleObj.allLineArr[i] + ','
            }
            $scope.resuleObj.Lines = $scope.resuleObj.Lines.substr(0, $scope.resuleObj.Lines.length - 1)
            // console.log($scope.resuleObj.Lines)
        }
        /**运营商、设备、网络三块多选区域的回显 */
        $scope.checkBoxBackshow = function (operator, machine, Lines) {
            var operatorArr = [ ]
            var machineArr = [ ]
            var LinesArr = [ ]
            $scope.checkboxListOperator[0].ifchosed = false
            $scope.checkboxListMachine[0].ifchosed = false
            $scope.checkboxListLine[0].ifchosed = false
            if (operator) {
                operatorArr = operator.split(',')
            }else if (!operator) {
                $scope.checkboxListOperator[0].ifchosed = true
            }
            if (machine) {
                machineArr = machine.split(',')
            }else if (!machine) {
                $scope.checkboxListMachine[0].ifchosed = true
            }
            if (Lines) {
                LinesArr = Lines.split(',')
            }else if (!Lines) {
                $scope.checkboxListLine[0].ifchosed = true
            }
            // operatorArr=operator.split(',')
            // machineArr=machine.split(',')
            // LinesArr=Lines.split(',')
            for (var a = 0;a < operatorArr.length;a++) { // 运营商回显
                for (var i = 0;i < $scope.checkboxListOperator.length;i++) {
                    if ($scope.checkboxListOperator[i].count === operatorArr[a]) {
                        $scope.checkboxListOperator[i].ifchosed = true
                    }
                }
            }
            for (var a = 0;a < machineArr.length;a++) { // 设备回显
                for (var i = 0;i < $scope.checkboxListMachine.length;i++) {
                    if ($scope.checkboxListMachine[i].count === machineArr[a]) {
                        $scope.checkboxListMachine[i].ifchosed = true
                    }
                }
            }
            for (var a = 0;a < LinesArr.length;a++) { // 网络选择回显
                for (var i = 0;i < $scope.checkboxListLine.length;i++) {
                    if ($scope.checkboxListLine[i].count === LinesArr[a]) {
                        $scope.checkboxListLine[i].ifchosed = true
                    }
                }
            }
        }

        /*以下为时间定向弹框*/
        // $scope.showTimeLayer = false
        // $scope.ifShowTimeLayer = function () {  //打开或关闭时间选择弹框
        //     $scope.showTimeLayer = !$scope.showTimeLayer
        // }
        /* 以下为兴趣人群定向 */
        // $scope.showGroupLayer = false
        // $scope.ifShowGroupLayer = function () {  //打开或关闭兴趣弹框
        //     $scope.showGroupLayer = !$scope.showGroupLayer
        // }
        /* 以下为选择行业的弹框,本期先不做 */
        // $scope.showIndustryLayer=false
        // $scope.ifShowIndustryLayer = function () {  //打开或关闭行业选择弹框
        //   $scope.showIndustryLayer = !$scope.showIndustryLayer
        // }
        /**只要选中不限，则输入框中的值清空 */
        $scope.clearData = function () {
            if ($scope.resuleObj.everydayMoney === true) {
                $scope.resuleObj.everydayMoneyInput = ''
            }
            if ($scope.resuleObj.allMoney === true) {
                $scope.resuleObj.allMoneyInput = ''
            }
            if ($scope.resuleObj.allPublic === true) {
                $scope.resuleObj.allPublicInput = ''
            }
            if ($scope.resuleObj.allClick === true) {
                $scope.resuleObj.allClickInput = ''
            }
            if ($scope.resuleObj.dayCount === true) {
                $scope.resuleObj.dayCountInput = ''
            }
            if ($scope.resuleObj.hourCount === true) {
                $scope.resuleObj.hourCountInput = ''
            }
        }
        /**检验策略每日投放预算 */
        $scope.checkeverydayMoneyInput = function () {
            if ($scope.resuleObj.everydayMoneyInput === '' && $scope.resuleObj.everydayMoney === false) {
                $scope.alertModel({
                    text: '请输入每日投放预算', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.everydayMoneyInput <= 0 && $scope.resuleObj.everydayMoney === false) {
                $scope.resuleObj.everydayMoneyInput = ''
                $scope.alertModel({
                    text: '请输入大于0的金额', // 内容
                    resCode: '00001'
                })
                return false
            }
            if (!(/^\d+(?:\.\d{0,2})?$/).test($scope.resuleObj.everydayMoneyInput) && $scope.resuleObj.everydayMoney === false) {
                $scope.resuleObj.everydayMoneyInput = ''
                $scope.alertModel({
                    text: '请输入最多两位小数的金额数', // 内容
                    resCode: '00001'
                })
                return false
            }
        }
        /**检验策略总投放预算 */
        $scope.checkallMoneyInput = function () {
            if ($scope.resuleObj.allMoneyInput === '' && $scope.resuleObj.allMoney === false) {
                $scope.alertModel({
                    text: '请输入总投放预算', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.allMoneyInput <= 0 && $scope.resuleObj.allMoney === false) {
                $scope.resuleObj.allMoneyInput = ''
                $scope.alertModel({
                    text: '请输入大于0的金额', // 内容
                    resCode: '00001'
                })
                return false
            }
            if (!(/^\d+(?:\.\d{0,2})?$/).test($scope.resuleObj.allMoneyInput) && $scope.resuleObj.allMoney === false) {
                $scope.resuleObj.allMoneyInput = ''
                $scope.alertModel({
                    text: '请输入最多两位小数的金额数', // 内容
                    resCode: '00001'
                })
                return false
            }
        }
        /**检验策略总曝光数上限 */
        $scope.checkallPublicInput = function () {
            if ($scope.resuleObj.allPublicInput === '' && $scope.resuleObj.allPublic === false) {
                $scope.alertModel({
                    text: '请输入策略总曝光数上限', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ((/^[0-9]*[1-9][0-9]*$/).test($scope.resuleObj.allPublicInput) && $scope.resuleObj.allPublic === false) {
                $scope.alertModel({
                    text: '请输入大于0的整数', // 内容
                    resCode: '00001'
                })
                return false
            }
        }
        /**检验策略总点击数上限*/
        $scope.checkallClickInput = function () {
            if ($scope.resuleObj.allClickInput === '' && $scope.resuleObj.allClick === false) {
                $scope.alertModel({
                    text: '请输入策略总点击数上限', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ((/^[0-9]*[1-9][0-9]*$/).test($scope.resuleObj.allClickInput) && $scope.resuleObj.allClick === false) {
                $scope.alertModel({
                    text: '请输入大于0的整数', // 内容
                    resCode: '00001'
                })
                return false
            }
        }
        /**检验每个受众每日投放频次*/
        $scope.checkdayCountInput = function () {
            if ($scope.resuleObj.dayCountInput === '' && $scope.resuleObj.dayCount === false) {
                $scope.alertModel({
                    text: '请输入每个受众每日投放频次', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ((/^[0-9]*[1-9][0-9]*$/).test($scope.resuleObj.dayCountInput) && $scope.resuleObj.dayCount === false) {
                $scope.alertModel({
                    text: '请输入大于0的整数', // 内容
                    resCode: '00001'
                })
                return false
            }
        }
        /**检验每个受众每小时投放频次*/
        $scope.checkhourCountInput = function () {
            if ($scope.resuleObj.hourCountInput === '' && $scope.resuleObj.hourCount === false) {
                $scope.alertModel({
                    text: '请输入每个受众每小时投放频次', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ((/^[0-9]*[1-9][0-9]*$/).test($scope.resuleObj.hourCountInput) && $scope.resuleObj.hourCount === false) {
                $scope.alertModel({
                    text: '请输入大于0的整数', // 内容
                    resCode: '00001'
                })
                return false
            }
        }
        /**最后总的验证 */
        $scope.checkAllInput = function () {
            if ($scope.resuleObj.everydayMoney === false && $scope.resuleObj.everydayMoneyInput === '') {
                $scope.alertModel({
                    text: '请输入每日投放预算', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.allMoney === false && $scope.resuleObj.allMoneyInput === '') {
                $scope.alertModel({
                    text: '请输入总投放预算', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.allPublic === false && $scope.resuleObj.allPublicInput === '') {
                $scope.alertModel({
                    text: '请输入策略总曝光数上限', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.allClick === false && $scope.resuleObj.allClickInput === '') {
                $scope.alertModel({
                    text: '请输入策略总点击数上限', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.dayCount === false && $scope.resuleObj.dayCountInput === '') {
                $scope.alertModel({
                    text: '请输入每个受众每日投放频次', // 内容
                    resCode: '00001'
                })
                return false
            }
            if ($scope.resuleObj.hourCount === false && $scope.resuleObj.hourCountInput === '') {
                $scope.alertModel({
                    text: '请输入每个受众每小时投放频次', // 内容
                    resCode: '00001'
                })
                return false
            }
            // $scope.checkeverydayMoneyInput()
            // $scope.checkallMoneyInput()
            // $scope.checkallPublicInput()
            // $scope.checkallClickInput()
            // $scope.checkdayCountInput()
            // $scope.checkhourCountInput()
        }

        /**返回操作 */
        $scope.backto = function () {
            $state.go('main.zzy.zzyLaunchPlan.planDetail',{adPlanId: $scope.planId})
        }
        $scope.tradingArea = []

        // /**保存操作 */
        // $scope.save = function () {
        //     // console.log($scope.chosedObj)
        //     // console.log($scope.chosedObj)
        //     if ($scope.checkAllInput() !== false) {
        //         $scope.planName = $state.params.planName
        //         $scope.planId = $state.params.planId
        //         $scope.budgetType = $state.params.budgetType
        //         /**推广计划策略提交接口 - 张新强 */
        //         ajaxRquest.getData('/popularManage/addTactics', {
        //             planId: $state.params.planId,
        //             accountType: $.cookie('utmSource') == '2' ? '3' : $.cookie('accountType'),
        //             budgetType: $state.params.budgetType,
        //             timeSlot: $scope.resuleObj.time == '1' ? $scope.chosedObj : {}, // 时间定向
        //             ipType: $scope.resuleObj.IPlist, // ip定向类型
        //             includedIpsets: $scope.resuleObj.IPlist == '1' ? $scope.whiteEndData : $scope.resuleObj.IPlist == '2' ? $scope.blackEndData : {}, // ip定向数据
        //             interestGroups: $scope.resuleObj.group == '1' ? $scope.chosedList : [], // 兴趣人群定向,
        //             regionalTypes: $scope.resuleObj.area,
        //             tradingArea: $scope.resuleObj.area == '2' && $scope.tradingAreaTypes == '1' ? $scope.tradingArea : undefined,
        //             scenePackage: $scope.resuleObj.package == '0' ? '0' : $scope.showAdsList.length == 0 ? '' : $scope.showAdsList, // 流量场景包已选广告位
        //             customTradingArea: $scope.resuleObj.area == '2' && $scope.tradingAreaTypes == '2' ? $scope.circleList : undefined,
        //             targetLocation1: $scope.selectedPlace, //
        //             targetCarriers: $scope.resuleObj.operator, // 移动运营商定向（0：不限，1：移动，2：联通，3：电信，4：铁通）
        //             targetConnectTypes: $scope.resuleObj.Lines, // 移动联网方式定向(0:不限,1:WIFI,3:蜂窝-2G,4:蜂窝-3G,5:蜂窝-4G)
        //             targetDeviceTypes: $scope.resuleObj.machine, // 移动投放设备定向（0：不限，1：iPhone,2:Android,3:iPad)
        //             dailyExpend: $scope.resuleObj.everydayMoneyInput ? $scope.resuleObj.everydayMoneyInput : '-1', // 每日投放预算
        //             countExpend: $scope.resuleObj.allMoneyInput ? $scope.resuleObj.allMoneyInput : '-1', // 总投放预算
        //             lifeCycleImpressionCapping: $scope.resuleObj.allPublicInput ? $scope.resuleObj.allPublicInput : '-1', // 计划周期内总曝光次数上限，-1表示不限制，默认值为-1
        //             lifeCycleClickCapping: $scope.resuleObj.allClickInput ? $scope.resuleObj.allClickInput : '-1', // 计划周期内总点击次数上限，-1表示不限制，默认值为-1
        //             adDeliveryFrequencyPerDay: $scope.resuleObj.dayCountInput ? $scope.resuleObj.dayCountInput : '-1', // 每个受众每日投放频次上限，-1表示不限制，默认值为-1
        //             adDeliveryFrequencyPerHour: $scope.resuleObj.hourCountInput ? $scope.resuleObj.hourCountInput : '-1' // 每个受众每小时投放频次上限，-1表示不限制，默认值为-1
        //         }).then(function (res) {
        //             if (res.resCode == '00000') {
        //                 $state.go('main.extension.planList01')
        //             }else {
        //                 $scope.alertModel({
        //                     text: res.resMsg, // 内容
        //                     resCode: res.resCode
        //                 })
        //             }
        //         })
        //     }
        // }
        /**推广计划策略查询接口 - 张新强 */
        $.ajax({
            url : $scope.app.project_name+'/zzyLaunchPlan/queryTactics',
            data: {
                planId: $state.params.adPlanId,
                accountType: '3'
            }
        }).then(function (res) {
            console.log(res)
            if (res.httpCode == 200 && res.data) {
                $scope.$apply(function () {
                    $scope.resuleObj.area = res.data.regionalTypes?res.data.regionalTypes:'0'
                    $scope.circleList = res.data.customTradingArea ? JSON.parse(res.data.customTradingArea) : []; // 自定义商圈列表
                    $scope.tradingArea = res.data.tradingArea ? JSON.parse(res.data.tradingArea) : []; // 选择商圈列表

                    $scope.chosedObj = res.data.timeSlot ? JSON.parse(res.data.timeSlot) : '0'

                    $scope.resuleObj.IPlist = res.data.ipType == '' || res.data.ipType == undefined ? 0 : res.data.ipType; // //ip定向类型
                    $scope.whiteList = res.data.ipType == '1' ? res.data.includedIpsets : []; // ip定向白名单的数据
                    $scope.blackList = res.data.ipType == '2' ? res.data.includedIpsets : []; // ip定向黑名单的数据
                    $scope.chosedList = res.data.interestGroups ? JSON.parse(res.data.interestGroups) : []
                    $scope.selectedPlace = res.data.targetLocation1 ? JSON.parse(res.data.targetLocation1) : []; // 行政区域已选择列表
                    $scope.showAdsList = res.data.scenePackage == '' || res.data.scenePackage == undefined || res.data.scenePackage == '0' || res.data.scenePackage == 0 ? [] : JSON.parse(res.data.scenePackage); // 流量场景包已选择列表
                    $scope.resuleObj.package = res.data.scenePackage == '' || res.data.scenePackage == undefined || res.data.scenePackage == '0' ? '0' : '1'; // 场景包不限选项 回显
                    $scope.resuleObj.operator = res.data.targetCarriers
                    $scope.resuleObj.machine = res.data.targetDeviceTypes
                    $scope.resuleObj.Lines = res.data.targetConnectTypes
                    if ($scope.chosedObj === '0' || $scope.chosedObj === 0) { // 时间定向回显
                        $scope.resuleObj.time = '0'
                    }else {
                        $scope.resuleObj.time = '1'
                        console.log('有数据')
                        // $scope.chosedObj={}
                        $scope.backShow($scope.chosedObj)
                        $scope.showTimeLayer = false
                    }
                    if ($scope.chosedList === '0' || $scope.chosedList === 0 || $scope.chosedList.length==0) { // 兴趣人群定向回显
                        $scope.resuleObj.group = '0'
                        $scope.chosedList = []
                    } else {
                        $scope.resuleObj.group = '1'
                    }
                    $scope.checkBoxBackshow($scope.resuleObj.operator, $scope.resuleObj.machine, $scope.resuleObj.Lines) // 运营商、设备、网络三块多选区域的回显

                    $scope.resuleObj.everydayMoneyInput = res.data.dailyExpend // 往下为预算控制模块内的数据回显
                    $scope.resuleObj.allMoneyInput = res.data.countExpend
                    $scope.resuleObj.allPublicInput = res.data.lifeCycleImpressionCapping
                    $scope.resuleObj.allClickInput = res.data.lifeCycleClickCapping
                    $scope.resuleObj.dayCountInput = res.data.adDeliveryFrequencyPerDay
                    $scope.resuleObj.hourCountInput = res.data.adDeliveryFrequencyPerHour
                    if ($scope.resuleObj.everydayMoneyInput === '0' || $scope.resuleObj.everydayMoneyInput === 0 || !$scope.resuleObj.everydayMoneyInput) { // 判断是不限还是具体数值
                        $scope.resuleObj.everydayMoneyInput = ''
                        $scope.resuleObj.everydayMoney = true
                    }else {
                        $scope.resuleObj.everydayMoney = false
                    }
                    if ($scope.resuleObj.allMoneyInput === '0' || $scope.resuleObj.allMoneyInput === 0 || !$scope.resuleObj.allMoneyInput) {
                        $scope.resuleObj.allMoneyInput = ''
                        $scope.resuleObj.allMoney = true
                    }else {
                        $scope.resuleObj.allMoney = false
                    }
                    if ($scope.resuleObj.allPublicInput === '0' || !$scope.resuleObj.allPublicInput) {
                        $scope.resuleObj.allPublicInput = ''
                        $scope.resuleObj.allPublic = true
                    }else {
                        $scope.resuleObj.allPublic = false
                    }
                    if ($scope.resuleObj.allClickInput === '0' || !$scope.resuleObj.allClickInput) {
                        $scope.resuleObj.allClickInput = ''
                        $scope.resuleObj.allClick = true
                    }else {
                        $scope.resuleObj.allClick = false
                    }
                    if ($scope.resuleObj.dayCountInput === '0' || !$scope.resuleObj.dayCountInput) {
                        $scope.resuleObj.dayCountInput = ''
                        $scope.resuleObj.dayCount = true
                    }else {
                        $scope.resuleObj.dayCount = false
                    }
                    if ($scope.resuleObj.hourCountInput === '0' || !$scope.resuleObj.hourCountInput) {
                        $scope.resuleObj.hourCountInput = ''
                        $scope.resuleObj.hourCount = true
                    }else {
                        $scope.resuleObj.hourCount = false
                    }
                })
            } else {
               if(res.httpCode!=200){
                   $scope.alertModal({"content":"系统异常"});
               }
            }
        })

        // $scope.selectedPlace= [{"name":"安徽","id":"10001"},{"name":"安徽/安庆","id":"10001,20001"},{"name":"安徽/安庆/大观区","id":"10001,20001,30001"}]
        // chooseMedia 流量场景包方法 按钮回到不限
        $scope.isShowAdsListEmpty = function (v) {
            v && v.length != 0 ? $scope.resuleObj.package = '0' : $scope.resuleObj.package = '1'
        }
        $scope.isEmpty = function (a) {
            console.log(a)
            if (!a) {
                $scope.resuleObj.area = '0'
            }
        }
    }])
